package com.landinfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nls.client.AccessToken;
import com.landinfo.domain.DashboardConfiguration;
import com.landinfo.domain.DefaultConfigSetting;
import com.landinfo.repository.DashboardConfigRepository;
import com.landinfo.service.DashboardConfigService;
import com.landinfo.service.dto.DashboardConfigDTO;
import com.landinfo.service.mapper.DashboardConfigMapper;
import com.landinfo.web.rest.util.HttpRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Optional;

/**
 * Service Implementation for managing DashboardConfiguration.
 */
@Service
@Transactional
public class DashboardConfigServiceImpl implements DashboardConfigService {

    private final Logger log = LoggerFactory.getLogger(DashboardConfigServiceImpl.class);

    private final DashboardConfigRepository dashboardConfigRepository;

    private final DashboardConfigMapper dashboardConfigMapper;

    @Autowired
    DefaultConfigSetting defaultConfig;

    public DashboardConfigServiceImpl(DashboardConfigRepository dashboardConfigRepository, DashboardConfigMapper dashboardConfigMapper) {
        this.dashboardConfigRepository = dashboardConfigRepository;
        this.dashboardConfigMapper = dashboardConfigMapper;
    }

    @Override
    public DashboardConfigDTO save(DashboardConfigDTO dashboardConfigDTO) {
        log.debug("Request to save DashboardConfiguration : {}", dashboardConfigDTO);
        DashboardConfiguration dashboardConfiguration = dashboardConfigMapper.toEntity(dashboardConfigDTO);
        dashboardConfiguration = dashboardConfigRepository.save(dashboardConfiguration);
        return dashboardConfigMapper.toDto(dashboardConfiguration);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<DashboardConfigDTO> findAll(Pageable pageable) {
        log.debug("Request to get all DashboardConfigs");
        return dashboardConfigRepository.findAll(pageable)
            .map(dashboardConfigMapper::toDto);
    }


    @Override
    @Transactional(readOnly = true)
    public Optional<DashboardConfigDTO> findOne(String id) {
        log.debug("Request to get DashboardConfiguration : {}", id);
        return dashboardConfigRepository.findById(id)
            .map(dashboardConfigMapper::toDto);
    }

    @Override
    public void delete(String id) {
        log.debug("Request to delete DashboardConfiguration : {}", id);
        dashboardConfigRepository.deleteById(id);
    }

    @Override
    public Optional<DashboardConfigDTO> findByName(String name) {
        return dashboardConfigRepository.findByName(name).map(dashboardConfigMapper::toDto);
    }

    @Override
    public void deleteByName(String name) {
        dashboardConfigRepository.removeByName(name);
    }

    @Override
    public JSONObject getVoiceToken() {
        JSONObject result = new JSONObject();
        result.put("success", false);
        String key = defaultConfig.getVoiceAccessKey();
        String secret = defaultConfig.getVoiceAccessSecret();
        if (key == null || "".equals(key.trim())) {
            result.put("msg", "获取失败:未获取到配置文件项key");
            return result;
        }
        if (secret == null || "".equals(secret.trim())) {
            result.put("msg", "获取失败:未获取到配置文件项secret");
            return result;
        }

        String token2DashBoardConfigId = "ali_voice_token";
        String token = null;
        Long expireTime = null;
        JSONObject lastTokenObj;
        Optional<DashboardConfiguration> dashboardConfigurationOptional = dashboardConfigRepository.findById(token2DashBoardConfigId);
        if (dashboardConfigurationOptional.isPresent()) {
            String content = dashboardConfigurationOptional.get().getContent();
            if (content != null && !content.equals("")) {
                lastTokenObj = JSON.parseObject(content);
                if (lastTokenObj.get("token") != null) {
                    token = lastTokenObj.getString("token");
                }
                if (lastTokenObj.get("expireTime") != null) {
                    expireTime = lastTokenObj.getLong("expireTime");
                }
            }
        }

        boolean isOk = false;
        if (token != null && expireTime != null) {
            Instant instant = Instant.ofEpochSecond(expireTime);
            ZonedDateTime beforeTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
            ZonedDateTime nowTime = ZonedDateTime.now();
            if (beforeTime.isAfter(nowTime)) {
                isOk = true;
            }
        }

        if (!isOk) {
            try {
                AccessToken accessToken = new AccessToken(key, secret);
                accessToken.apply();
                token = accessToken.getToken();
                expireTime = accessToken.getExpireTime();
            } catch (IOException e) {
                result.put("msg", "获取失败:" + e.getMessage());
                return result;
            }

            if (token != null) {
                JSONObject data = new JSONObject();
                data.put("token", token);
                data.put("expireTime", expireTime);
                DashboardConfiguration dashboardConfiguration=new DashboardConfiguration();
                dashboardConfiguration.setId(token2DashBoardConfigId);
                dashboardConfiguration.setContent(JSON.toJSONString(data));
                dashboardConfiguration.setName(token2DashBoardConfigId);
                dashboardConfiguration.setModuleName("语音播报token");
                dashboardConfigRepository.save(dashboardConfiguration);

                result.put("token", token);
                result.replace("success", true);
            } else {
                result.put("msg", "获取token失败！");
            }
            return result;
        } else {
            result.replace("success", true);
            result.put("token", token);
            return result;
        }
    }
}
